/**
 * 代码摘自https://github.com/hustcc/timeago.js
 */
const SEC_ARRAY = [
  60, // 60 seconds in 1 min
  60, // 60 mins in 1 hour
  24, // 24 hours in 1 day
  7, // 7 days in 1 week
  365 / 7 / 12, // 4.345238095238096 weeks in 1 month
  12, // 12 months in 1 year
];

const ZH_CN = ['秒', '分钟', '小时', '天', '周', '个月', '年'];

function format(diff ,idx) {
  if (idx === 0) return ['刚刚', '片刻后'];
  const unit = ZH_CN[~~(idx / 2)];
  return [`${diff} ${unit}前`, `${diff} ${unit}后`];
}

/**
 * 将字符串｜数字转成Date对象
 * format Date / string / timestamp to timestamp
 * @param input
 * @returns {*}
 */
export function toDate(input) {
  if (input instanceof Date) return input;
  // @ts-ignore
  if (!isNaN(input) || /^\d+$/.test(input)) return new Date(parseInt(input));
  input = (input || '')
    // @ts-ignore
    .trim()
    .replace(/\.\d+/, '') // remove milliseconds
    .replace(/-/, '/')
    .replace(/-/, '/')
    .replace(/(\d)T(\d)/, '$1 $2')
    .replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC
    .replace(/([+-]\d\d):?(\d\d)/, ' $1$2'); // -04:00 -> -0400
  return new Date(input);
}

/**
 * format the diff second to *** time ago, with setting locale
 * @param diff
 * @param localeFunc
 * @returns
 */
export function formatDiff(diff) {
  const agoIn = diff < 0 ? 1 : 0;
  diff = Math.abs(diff);
  const totalSec = diff;

  let idx = 0;

  for (; diff >= SEC_ARRAY[idx] && idx < SEC_ARRAY.length; idx++) {
    diff /= SEC_ARRAY[idx];
  }

  diff = Math.floor(diff);

  idx *= 2;

  if (diff > (idx === 0 ? 9 : 1)) idx += 1;
  return format(diff, idx, totalSec)[agoIn].replace('%s', diff.toString());
}

/**
 * calculate the diff second between date to be formatted an now date.
 * @param date
 * @param relativeDate
 * @returns {number}
 */
export function diffSec(date, relativeDate) {
  const relDate = relativeDate ? toDate(relativeDate) : new Date();
  return (+relDate - +toDate(date)) / 1000;
}

export function nextInterval(diff) {
  let rst = 1,
    i = 0,
    d = Math.abs(diff);
  for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY.length; i++) {
    diff /= SEC_ARRAY[i];
    rst *= SEC_ARRAY[i];
  }
  d = d % rst;
  d = d ? rst - d : rst;
  return Math.ceil(d);
}